import asyncio
import websockets
import json
import ssl

# SSL配置
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain(certfile="testcall.shengtucuican.com.pem", keyfile="testcall.shengtucuican.com.key")

print(f"\n============服务上线地址 ws://localhost:9999============")

# 房间
rooms = {}
async def handle_client(websocket, path):
    # 连接打开事件
    print("WebSocket连接成功.")

    await websocket.send(json.dumps({
        'code':'repConnect',
        'data':'连接成功'
    }))
    try:
        async for message in websocket:
            # 消息接收事件
            print(message)
            res = json.loads(message)

            # 加入房间事件
            if res['code']=='joinRoom':
                # 获取房间号
                room_name = res['data']
                # 验证房间是否存在
                if room_name not in rooms:
                    # 创建空房间
                    rooms[room_name] = []
                # 用户加入房间
                rooms[room_name].append(websocket)
                await websocket.send(json.dumps({
                    'code': 'repJoinRoom',
                    'data': '加入房间成功'
                }))

            # 呼叫事件广播
            if res['code']=='collRemote':
                # 获取房间号
                room_name = res['data']
                await broadcastRoom(room_name,json.dumps({
                    'code': 'repCollRemote',
                    'data': room_name
                }))

            # 用户接听事件
            if res['code']=='acceptCall':
                # 获取房间号
                room_name = res['data']
                await broadcastRoom(room_name,json.dumps({
                    'code': 'repAcceptCall',
                    'data': room_name
                }))

            # 用户挂断事件
            if res['code']=='hangupCall':
                # 获取房间号
                room_name = res['data']
                # 广播offer
                await broadcastRoom(room_name,json.dumps({
                    'code': 'repHangupCall',
                    'data': room_name
                }))

            # 发布offer事件
            if res['code']=='sendOffer':
                # 获取房间号
                room_name = res['data']
                offer = res['offer']
                # 广播offer
                await broadcastRoom(room_name,json.dumps({
                    'code': 'repSendOffer',
                    'data': offer
                }))

            # 发布sendAnswer事件
            if res['code']=='sendAnswer':
                # 获取房间号
                room_name = res['data']
                answer = res['answer']
                # 广播offer
                await broadcastRoom(room_name,json.dumps({
                    'code': 'repSendAnswer',
                    'data': answer
                }))

            # 发布candidate事件
            if res['code']=='sendCandidate':
                # 获取房间号
                room_name = res['data']
                candidate = res['candidate']
                # 广播offer
                await broadcastRoom(room_name,json.dumps({
                    'code': 'repSendCandidate',
                    'data': candidate
                }))

            await websocket.send(message)  # 可以选择性地将接收到的消息回发给客户端
    except websockets.exceptions.ConnectionClosedOK:
        # 正常关闭事件
        print("WebSocket connection closed normally.")

    except Exception as e:
        # 其他异常导致的关闭事件
        print(f"WebSocket connection error: {e}")

async def broadcastRoom(room_name, message):
    # 向指定房间的所有客户端发送消息
    if room_name in rooms:
        for client in rooms[room_name]:
            print('client',client)
            await client.send(message)

# start_server = websockets.serve(handle_client, "0.0.0.0", 9999,ssl=ssl_context)
start_server = websockets.serve(handle_client, "0.0.0.0", 9999)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
